import { IGroupItem } from '@/utils/interfaces'
import { apiStore } from '@/utils/store/apiStore'

export const expandableSorter = (a: IListItem, b: IListItem) => {
    if (a.type !== 'api' || b.type !== 'api') {
        return 0
    }
    const aExpandable = !!a.expects?.length || !!a.variables?.length
    const bExpandable = !!b.expects?.length || !!b.variables?.length
    if (aExpandable && !bExpandable) {
        return -1
    }
    if (!aExpandable && bExpandable) {
        return 1
    }
    return 0
}

export const enableSorter = (a: IListItem, b: IListItem) => {
    if (!!a?.enabled === !!b?.enabled) {
        return expandableSorter(a, b)
    }
    return a?.enabled ? -1 : 1
}

export const useGroup = (group?: IGroupItem | null) => {
    // 当前分组下的api列表
    const [apiItems, setApiItems] = useState<IApiItem[]>([])
    // 当前分组id
    const [groupId, setGroupId] = useState<string | undefined>(group?.id)

    // 更新当前分组下的api列表以及组列表
    const updateApiItems = async (parentId?: string) => {
        const prentId = parentId || ''
        const list = await apiStore.getList(prentId, 'api')
        list.sort(enableSorter)
        setApiItems(list as IApiItem[])
    }

    // 更新当前分组id
    const updateGroupId = async (id?: string) => {
        setGroupId(id)
        updateApiItems(id)
    }

    // 初始化
    useEffect(() => {
        updateGroupId(group?.id)
    }, [])

    return {
        apiItems,
        groupId,
        updateGroupId,
        updateApiItems,
    }
}
